<template>
  <div class="basicSetting">
    <!-- 页面头部 -->
    <a-page-header title="企业基础设置"> </a-page-header>
    <section class="form">
      <a-form
        layout="horizontal"
        v-bind="{
          labelCol: {
            span: 4,
          },
          wrapperCol: {
            span: 14,
          },
        }"
      >
        <a-form-item label="企业名称" v-bind="validateInfos.company">
          <a-input
            placeholder="请输入企业名称"
            v-model:value="modelRef.company"
          />
        </a-form-item>
        <a-form-item label="企业简称" v-bind="validateInfos.name">
          <a-input placeholder="请输入企业简称" v-model:value="modelRef.name" />
        </a-form-item>
        <a-form-item label="企业邀请码" v-if="!isWorkAiOrg">
          <section class="code">
            <span class="join-code">{{ joinCode }}</span>
            <a-button shape="circle" type="link" @click="reloadCode">
              <template #icon>
                <SyncOutlined />
              </template>
            </a-button>
            <a-button class="ml-10" @click="copyCode">
              <template #icon><CopyOutlined /></template>
              复制
            </a-button>
          </section>
        </a-form-item>
        <a-form-item label="企业介绍" v-bind="validateInfos.info">
          <a-textarea
            v-model:value="modelRef.info"
            placeholder="请输入企业介绍"
            :auto-size="{ minRows: 4, maxRows: 6 }"
          />
        </a-form-item>
        <a-form-item
          label="企业水印"
          v-bind="validateInfos.open_page_water"
          extra="机构后台页面背景是否添加企业水印，修改配置后手动刷新页面即可生效。"
        >
          <a-switch
            v-model:checked="modelRef.open_page_water"
            checkedValue="1"
            unCheckedValue="0"
          />
        </a-form-item>
        <a-form-item>
          <template #label>
            <span style="margin-right: 5px">Logo</span>
            <a-tooltip>
              <template #title>建议上传白底图片，用于在招商平台展示</template>
              <span><QuestionCircleOutlined /></span>
            </a-tooltip>
          </template>
          <a-upload
            :action="imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            :multiple="false"
            v-model:file-list="fileList"
            list-type="picture-card"
            @change="handleUploadChange"
            name="image"
            :data="{ dir: 'org_basic_setting' }"
            accept="image/jpg,image/jpeg,image/gif,image/png"
          >
            <div v-if="!fileList.length">
              <plus-outlined></plus-outlined>
              <div>上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item>
          <template #label>
            <span style="margin-right: 5px">正方形Logo</span>
            <a-tooltip>
              <template #title>建议上传 200 * 200 的透明背景白色图片</template>
              <span><QuestionCircleOutlined /></span>
            </a-tooltip>
          </template>
          <a-upload
            :action="imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            :multiple="false"
            v-model:file-list="sLogoList"
            list-type="picture-card"
            @change="handleSLogoUpload"
            name="image"
            :data="{ dir: 'org_basic_setting' }"
            accept="image/jpg,image/jpeg,image/gif,image/png"
          >
            <div v-if="!sLogoList.length">
              <plus-outlined></plus-outlined>
              <div>上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="所属地" v-bind="validateInfos.area">
          <a-cascader
            v-model:value="modelRef.area"
            :options="areaOptions"
            :load-data="loadAreaData"
            placeholder="请选择省市区"
            change-on-select
            @change="areaSelectChange"
          />
        </a-form-item>
        <a-form-item label="联系方式">
          <a-input
            placeholder="请输入企业联系方式"
            v-model:value="modelRef.tel"
          />
        </a-form-item>
        <a-form-item label="联系地址" v-bind="validateInfos.address">
          <a-input
            placeholder="请输入企业联系地址"
            v-model:value="modelRef.address"
          />
        </a-form-item>
        <a-form-item v-bind="validateInfos.clue" v-if="!isWorkAiOrg">
          <template #label>
            <span style="margin-right: 5px">招商热线</span>
            <a-tooltip>
              <template #title
                >用于在招商平台作为热线电话， 不使用招商平台请忽略</template
              >
              <span><QuestionCircleOutlined /></span>
            </a-tooltip>
          </template>
          <a-row align="middle">
            <a-col style="width: 49%">
              <a-input
                style="width: 100%"
                placeholder="请输入招商热线"
                v-model:value="modelRef.clue_tel"
              />
            </a-col>
            <a-col style="width: 2%; text-align: center">--</a-col>
            <a-col style="width: 49%">
              <a-input
                style="width: 100%"
                placeholder="请输入招商时间，例：早9:00 — 晚8：30"
                v-model:value="modelRef.clue_time"
              />
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item
          label="域名前缀"
          v-bind="validateInfos.domain_prefix"
          extra="企业的域名前缀提交后将不可更改"
        >
          <a-input
            placeholder="请输入企业域名前缀"
            v-model:value="modelRef.domain_prefix"
            :disabled="domainDisabled"
          />
        </a-form-item>
        <a-form-item
          label="工号前缀"
          v-bind="validateInfos.org_prefix"
          v-if="!isWorkAiOrg"
        >
          <a-input
            placeholder="请输入企业工号前缀"
            v-model:value="modelRef.org_prefix"
          />
        </a-form-item>
        <a-form-item
          label="是否可修改真实姓名"
          v-bind="validateInfos.change_self_realname"
          v-if="!isWorkAiOrg"
        >
          <a-switch
            v-model:checked="modelRef.change_self_realname"
            checkedValue="1"
            unCheckedValue="0"
          />
        </a-form-item>
        <a-form-item label="短信签名" v-if="org_sms_show">
          <a-textarea
            v-model:value="modelRef.org_sign_name"
            placeholder="请输入短信签名"
            :rows="3"
            disabled
          />
        </a-form-item>
        <a-form-item label="短信剩余数" v-if="org_sms_show">
          <a-input-number
            id="inputNumber"
            v-model:value="modelRef.org_sms_number"
            :min="1"
            style="width: 120px"
            disabled
          />
        </a-form-item>
      </a-form>
      <div class="option">
        <a-button
          type="primary"
          @click.prevent="onSubmit"
          size="large"
          style="width: 100px"
        >
          保存
        </a-button>
      </div>
    </section>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, toRaw, computed } from "vue";
import { Form, message } from "ant-design-vue";
import {
  SyncOutlined,
  CopyOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { QuestionCircleOutlined } from "@ant-design/icons-vue";
import store from "../../../store/index";
const useForm = Form.useForm;
export default defineComponent({
  name: "companyBasicInfo",
  components: {
    SyncOutlined,
    CopyOutlined,
    QuestionCircleOutlined,
    PlusOutlined,
  },
  setup() {
    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      company: "",
      name: "",
      info: "",
      tel: "",
      address: "",
      domain_prefix: "",
      org_prefix: "",
      area: [],
      change_self_realname: "0",
      open_page_water: "1",
      clue_tel: "",
      clue_time: "",
      logo: "",
      square_logo: "",
    });
    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      company: [
        { required: true, message: "企业名称为必填项", trigger: "blur" },
      ],
      area: [
        {
          required: true,
          validator: (rules, value) => areaValidator(value),
          trigger: "blur",
        },
      ],
      // tel: [
      //   {
      //     validator: (rules, value) => regValidator(value, "tel"),
      //     trigger: "blur",
      //   },
      // ],
      domain_prefix: [
        {
          validator: (rules, value) => regValidator(value, "domain_prefix"),
          trigger: "blur",
        },
      ],
      org_prefix: [
        {
          validator: (rules, value) => regValidator(value, "org_prefix"),
          trigger: "blur",
        },
      ],
    });

    const areaValidator = async (value) => {
      if (!value.length) {
        return Promise.reject("企业所属地区为必填项");
      }
      if (value.length < 2) {
        return Promise.reject("企业所属地区至少选择两级");
      }
      return Promise.resolve();
    };

    const regValidator = async (value, type) => {
      let reg = undefined;
      if ("tel" == type && value) {
        reg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
        if (!reg.test(value)) {
          return Promise.reject("请输入正确的手机号码");
        }
      }
      if (("domain_prefix" == type || "org_prefix" == type) && value) {
        // 只能使用英文字母（a~z，不区分大小写）、数字（0~9）以及连接符（-）
        reg = /^(?!-)(?!.*?-$)[a-zA-Z0-9-]+$/;
        if (!reg.test(value)) {
          return Promise.reject(
            `${
              "domain_prefix" == type ? "域名" : "工号"
            }前缀只能使用英文字母（a~z，不区分大小写）、数字（0~9）以及连接符（-）,且头部和尾部不能是连接符（-）`
          );
        }
        console.log(value.length);
        if ("domain_prefix" == type && value.length > 63) {
          return Promise.reject("域名前缀的长度不超过63位");
        }
      }
      return Promise.resolve();
    };
    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate()
        .then(() => {
          console.log(selectedAreaOptions);
          let params = {
            ...toRaw(modelRef),
            needMsg: true,
          };
          params.province_id = selectedAreaOptions[0].value;
          params.city_id = selectedAreaOptions[1].value;
          params.district_name = `${selectedAreaOptions[0].label},${selectedAreaOptions[1].label}`;
          delete params.area;
          console.log(params);
          request.put("/org", "/setting/basic", params).then((res) => {
            getDetail();
            message.success(res.msg || "保存成功！");
          });
        })
        .catch((err) => {
          console.log("error", err);
        });
    };

    /**
     * @description: 重置表单
     */
    const resetForm = () => {
      resetFields();
    };

    // 获取详情
    const joinCode = ref("");
    let detail = {};
    const domainDisabled = ref(false);
    const getDetail = () => {
      detail = {};
      request.get("/org", "/setting/basic").then((res) => {
        detail = res.orgBasic;
        setModelRef({
          company: detail.company,
          name: detail.name,
          info: detail.info,
          address: detail.address,
          tel: detail.tel,
          area: detail.city_id ? [detail.province_id, detail.city_id] : [],
          domain_prefix: detail.domain_prefix,
          org_prefix: detail.org_prefix,
          change_self_realname: detail.extra_config
            ? detail.extra_config.change_self_realname || 0
            : 0,
          open_page_water: detail.extra_config
            ? detail.extra_config.open_page_water || 1
            : 1,
          clue_tel: detail.clue_tel,
          clue_time: detail.clue_time,
          logo: detail.logo,
          square_logo: detail.square_logo,
        });
        if (detail.domain_prefix) {
          domainDisabled.value = true;
        }
        getProvinceList(detail.province_id);
        joinCode.value = detail.join_code;
        if (detail.logo) {
          fileList.value = [
            {
              uid: "1",
              name: detail.logo,
              status: "done",
              url: detail.logo,
            },
          ];
        }
        if (detail.square_logo) {
          sLogoList.value = [
            {
              uid: "2",
              name: detail.square_logo,
              status: "done",
              url: detail.square_logo,
            },
          ];
        }
      });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    // 省市区
    const areaOptions = ref([]);
    let selectedAreaOptions = [];
    // 获取省
    const getProvinceList = (provinceId) => {
      selectedAreaOptions = [];
      request.get("/public", "/district/province_list").then((res) => {
        if (res.list) {
          areaOptions.value = res.list.map((item) => {
            const provinceItem = {
              value: item.area_code,
              label: item.name,
              level: 1,
              isLeaf: false,
            };
            if (provinceId && provinceItem.value == provinceId) {
              selectedAreaOptions.push(provinceItem);
              getCityByProvince(provinceItem);
            }
            return provinceItem;
          });
        }
      });
    };
    // 动态加载省市信息
    const loadAreaData = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      if (targetOption.level == 1) {
        // 请求市
        getCityByProvince(targetOption);
      }
    };
    const getCityByProvince = (province) => {
      request
        .get("/public", "/district/city_list", {
          province_id: province.value,
        })
        .then((res) => {
          if (res.list) {
            province.children = res.list.map((item) => {
              let city = {
                label: item.name,
                value: item.area_code,
                level: 2,
                isLeaf: true,
              };
              if (detail.city_id && city.value == detail.city_id) {
                selectedAreaOptions.push(city);
              }
              return city;
            });
            areaOptions.value = [...areaOptions.value];
          }
        });
    };

    // 监听省市区选择
    const areaSelectChange = (value, selectedOptions) => {
      selectedAreaOptions = selectedOptions;
    };

    // logo上传
    const fileList = ref([]);
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              modelRef.logo = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.logo = "";
      }
      fileList.value = resFileList;
    };

    const sLogoList = ref([]);
    const handleSLogoUpload = (info) => {
      const { file, fileList } = info;
      if (file && file.response && file.status == "done") {
        if (file.response.code == 1000) {
          // 上传成功
          modelRef.square_logo = file.url = file.response.data.fileUrl;
          sLogoList.value = [file];
        } else {
          // 上传失败
          message.error(file.response.msg || `文件“${file.name}”上传失败！`);
          sLogoList.value = [];
        }
      }
      if (!fileList.length) {
        modelRef.square_logo = "";
      }
    };
    // const beforeUpload = (file) => {
    //   return new Promise((resolve, reject) => {
    //     const isAccept = [
    //       "image/jpeg",
    //       "image/png",
    //       "image/jpg",
    //       "image/gif",
    //     ].includes(file.type);
    //     if (!isAccept) {
    //       message.error("只能上传png，gif，jpeg，jpg格式的图片！");
    //       reject();
    //     }
    //     resolve();
    //   });
    // };

    // 重新获取机构码
    const reloadCode = () => {
      request.get("/org", "/setting/getJoinCode").then((res) => {
        joinCode.value = res.join_code;
      });
    };

    // 复制文本
    const copyCode = () => {
      utils.copyText(joinCode.value);
    };

    const org_sms_show = ref(false);

    const getSmsConfig = () => {
      request.get("/message", "/org/sms/config").then((res) => {
        modelRef.org_sign_name = res.org_sign_name;
        modelRef.org_sms_number = res.org_sms_number;
        org_sms_show.value = res.org_sms_show;
      });
    };

    const init = () => {
      getDetail();
      getSmsConfig();
    };

    init();

    // 是否workAiOrg
    const isWorkAiOrg = computed(() => {
      if (
        store.getters.orgInfo &&
        store.getters.orgInfo.org_type &&
        store.getters.orgInfo.org_type == "workAi"
      ) {
        return true;
      } else {
        return false;
      }
    });

    return {
      modelRef,
      validateInfos,
      joinCode,
      onSubmit,
      resetForm,
      loadAreaData,
      areaSelectChange,
      areaOptions,
      imgAction: request.BASE_URL + "/public/system/uploadImage",
      handleUploadChange,
      fileList,
      reloadCode,
      copyCode,
      // beforeUpload,
      domainDisabled,
      sLogoList,
      handleSLogoUpload,
      isWorkAiOrg,

      org_sms_show,
    };
  },
});
</script>

<style lang="less" scoped>
.basicSetting {
  background: #fff;
  .form {
    padding: 20px;
    .code {
      height: 32px;
      display: flex;
      align-items: center;
      .join-code {
        font-size: 20px;
        line-height: 32px;
        font-weight: bold;
        margin-right: 10px;
      }
    }
  }
  .option {
    text-align: left;
    margin-top: 20px;
    margin-left: 16%;
  }
}
</style>
